//
//  MallShopSecondViewController.m
//  BaseFrame
//
//  Created by 吕金状 on 2017/8/10.
//  Copyright © 2017年 com.mxh. All rights reserved.
//

#import "MallShopSecondViewController.h"
#import "MallShopCollectionViewCell.h"
#import "StoreRecommendScreeningView.h"
#import "SearchViewController.h"
#import "MallShopTableViewCell.h"
#import "GoodListViewController.h"
#import "ShopGoodListViewController.h"
#import "MallShopSecondTableViewCell.h"

@interface MallShopSecondViewController ()<UICollectionViewDelegate , UICollectionViewDelegateFlowLayout , UICollectionViewDataSource , UITableViewDelegate , UITableViewDataSource>
{
    UIButton *rightButton;
    int chooseIndex;
    float offsetY;
}
Strong UIView *headView;
Strong NSArray *menuArray; /**<*/
Strong NSMutableArray *dataArray; /**<*/
Strong SDCycleScrollView *sdcView;
Strong UICollectionView *collectionView;
@property (nonatomic,strong) UITableView *tableView;
Strong NSArray *screeningArray; /**<*/

Assign int pstart;

@end

//网络
@implementation MallShopSecondViewController (NetWorking)

- (void)getBanner{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"levels":@"2"};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Advertisement/displayAd.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            NSString *str = [[NSURL URLOffsetIPWithString:responseObject[@"obj"][@"picture_path"]]absoluteString];
            self.sdcView.imageURLStringsGroup = @[str];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)getTitleData{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"lmId":self.lmId,
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Header_Management/showTwoTitleByFirstLevelTitle.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            self.menuArray = responseObject[@"obj"];
            NSLog(@"===============%@",self.menuArray);
            [self.view addSubview:self.tableView];
            [self getData:0];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}

- (void)showRecommended{
    [self showprogressHUD];
  
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Recommended_Categories/showRecommended.action" parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            self.screeningArray = responseObject[@"obj"];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


- (void)getData:(int)pstart{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"pstart":[NSString stringWithFormat:@"%d",pstart],
                                 @"psize":@"20",
                                 @"level":@"1"
                                 };
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Shop_Recommendation/showAllRecommendedStores.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if (pstart == 0) {
                self.pstart = 1;
                [self.dataArray removeAllObjects];
            }else{
                self.pstart ++;
            }
            [self.dataArray addObjectsFromArray:responseObject[@"obj"]];
            [self.tableView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        [self showError:error];
    }];
}

/**
 通过级别和推荐ID显示推荐店铺信息（分页）
 */
- (void)getDisplayAccordingToLevelAndRecommendationCategory:(int)pstart{
    [self showprogressHUD];
    NSDictionary *parameters = @{@"s_level":@"1",
                                 @"rc_id":self.screeningArray[chooseIndex][@"rc_id"],
                                 @"pstart":[NSString stringWithFormat:@"%d",pstart],
                                 @"psize":@"20"};
    [[AFAppDotNetAPIClient sharedClient] POST:@"LaundryMall/Shop_Recommendation/displayAccordingToLevelAndRecommendationCategory.action" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"responseStatus"] isEqualToString:@"0"]) {
            if (pstart == 0) {
                self.pstart = 1;
                [self.dataArray removeAllObjects];
            }else{
                self.pstart ++;
            }
            [self.dataArray addObjectsFromArray:responseObject[@"obj"]];
            [self.tableView reloadData];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}


@end

@implementation MallShopSecondViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    chooseIndex = 0;
    [self getBanner];
    [self showRecommended];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"search"] style:0 target:self action:@selector(searchEvent)];
    self.navigationItem.titleView = ({
        UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 7, SCREEN_WIDTH, 30)];
        btn.layer.borderWidth = .5;
        btn.layer.borderColor = [UIColor whiteColor].CGColor;
        btn.layer.masksToBounds = YES;
        btn.layer.cornerRadius = 15;
        [btn setTitle:@"搜索商品或店铺" forState:UIControlStateNormal];
        btn.titleLabel.font = DEF_FontSize_12;
        [btn addTarget:self action:@selector(searchEvent) forControlEvents:UIControlEventTouchUpInside];
        btn;
    });
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - init

- (SDCycleScrollView *)sdcView{
    if (!_sdcView) {
        _sdcView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150/WIDTH_5S_SCALE)];
        _sdcView.backgroundColor = getColor(mainColor);
        _sdcView.autoScrollTimeInterval = 3.0;
        _sdcView.backgroundColor = getColor(@"bfbfbf");
        _sdcView.pageControlDotSize = CGSizeMake(11, 11);
        _sdcView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
        _sdcView.currentPageDotImage = [UIImage imageNamed:@"homepage_banner_point"];
        _sdcView.pageDotImage = [UIImage imageNamed:@"homepage_banner_circle"];
        __block typeof(self) bSelf = self;
        _sdcView.clickItemOperationBlock = ^(NSInteger currentIndex) {
            
        };
        
    }
    return _sdcView;
}


- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 150 / WIDTH_5S_SCALE, SCREEN_WIDTH , 113 / WIDTH_5S_SCALE * (self.menuArray.count / 3 + (self.menuArray.count % 3 == 0 ? + 0 : + 1))) collectionViewLayout:flowLayout];
        [_collectionView registerClass:[MallShopSecondTableViewCell class] forCellWithReuseIdentifier:@"UICollectionView"];
        _collectionView.backgroundColor = getColor(@"ffffff");
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
    }
    return _collectionView;
}

- (UIView *)headView{
    if (!_headView) {
        _headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 150 / WIDTH_5S_SCALE + 30 / WIDTH_5S_SCALE + (113 / WIDTH_5S_SCALE * (self.menuArray.count / 3 + (self.menuArray.count % 3 == 0 ? + 0 : + 1))))];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 150 / WIDTH_5S_SCALE +  113 / WIDTH_5S_SCALE * (self.menuArray.count / 3 + (self.menuArray.count % 3 == 0 ? + 0 : + 1)), SCREEN_WIDTH, 0.5)];
        lineView.backgroundColor = getColor(dividerColor);
        
        UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 150 / WIDTH_5S_SCALE +  113 / WIDTH_5S_SCALE * (self.menuArray.count / 3 + (self.menuArray.count % 3 == 0 ? + 0 : + 1)) + 0.5, SCREEN_WIDTH, 30 / WIDTH_5S_SCALE)];
        UILabel *titleLabel  = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30 / WIDTH_5S_SCALE)];
        titleLabel.font = DEF_FontSize_14;
        titleLabel.textColor = getColor(textColor);
        titleLabel.textAlignment = NSTextAlignmentCenter;
        NSMutableAttributedString *attStr1 = [NSMutableAttributedString new];
        NSTextAttachment *seeAtt1 = [NSTextAttachment new];
        seeAtt1.bounds = CGRectMake(0,  3 / WIDTH_5S_SCALE, 40 / WIDTH_5S_SCALE, 3);
        seeAtt1.image = [UIImage imageNamed:@"divider_left"];
        [attStr1 appendAttributedString:[NSAttributedString attributedStringWithAttachment:seeAtt1]];
        [attStr1 appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" %@ ",@"店铺推荐"]]];
        NSTextAttachment *seeAtt2 = [NSTextAttachment new];
        seeAtt2.bounds = CGRectMake(0,  3 / WIDTH_5S_SCALE, 40 / WIDTH_5S_SCALE, 3);
        seeAtt2.image = [UIImage imageNamed:@"divider_right"];
        [attStr1 appendAttributedString:[NSAttributedString attributedStringWithAttachment:seeAtt2]];
        
        titleLabel.attributedText = attStr1;
        rightButton = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 40 / WIDTH_5S_SCALE , 5 / WIDTH_5S_SCALE, 30 / WIDTH_5S_SCALE, 20 / WIDTH_5S_SCALE)];
        [rightButton setImage:[UIImage imageNamed:@"xiala"] forState:UIControlStateNormal];
        [rightButton setImage:[UIImage imageNamed:@"huishou"] forState:UIControlStateSelected];
        [rightButton addTarget:self action:@selector(rightButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [bgView sd_addSubviews:@[titleLabel , rightButton]];
        bgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bgViewClick)];
        [bgView addGestureRecognizer:tap];
        [_headView sd_addSubviews:@[self.sdcView , self.collectionView , lineView , bgView]];
    }
    return _headView;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64) style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.sectionFooterHeight = .01;
        _tableView.sectionHeaderHeight = .01;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.tableFooterView = [UIView new];
        _tableView.tableHeaderView = self.headView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.backgroundColor = getColor(@"ffffff");
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [self getBanner];
            [self getData:0];
            chooseIndex = 0;
        }];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            if (chooseIndex == 0) {
                [self getData:self.pstart];
            }else{
                [self getDisplayAccordingToLevelAndRecommendationCategory:self.pstart];
            }
            
        }];
    }
    return _tableView;
}

#pragma mark - Event

- (void)bgViewClick{
    [self rightButtonClick:rightButton];
}

- (void)rightButtonClick:(UIButton *)sender{
    sender.selected = !sender.selected;
    StoreRecommendScreeningView *view = [[StoreRecommendScreeningView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) selectedHandle:^(NSString *str) {
        chooseIndex = [str intValue];
        [self getDisplayAccordingToLevelAndRecommendationCategory:0];
    }];
    view.getDisMissClick = ^{
        rightButton.selected = NO;
    };
    view.chooseIndex = chooseIndex;
    float hei = (150 / WIDTH_5S_SCALE +  113 / WIDTH_5S_SCALE * (self.menuArray.count / 3 + (self.menuArray.count % 3 == 0 ? + 0 : + 1))  + 30 / WIDTH_5S_SCALE + 0.5) - offsetY;
    view.offsetY = hei;
    view.dataArray = self.screeningArray;
    [view show];
}

- (void)searchEvent{
    SearchViewController *vc = [SearchViewController new];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    offsetY = scrollView.contentOffset.y;
    
    NSLog(@"%f",offsetY);
    //    self.navigationController.navigationBar.subviews[0].alpha = alpha;
}

#pragma mark - <UITableViewDelegate , UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MallShopTableViewCell *cell = [MallShopTableViewCell cellForTableView:tableView];
    cell.model = self.dataArray[indexPath.row];
    //cell.accessoryType = indexPath.row == 3 ?  UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    GoodListViewController *vc = [GoodListViewController new];
    vc.s_id = self.dataArray[indexPath.row][@"s_id"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 87 / WIDTH_5S_SCALE;
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.menuArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MallShopSecondTableViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UICollectionView" forIndexPath:indexPath];
    cell.model = self.menuArray[indexPath.row];
    
    return cell;
}

- (NSAttributedString *)getAttributeName:(NSString *)name{
    NSMutableAttributedString *attStr = [NSMutableAttributedString new];
    NSAttributedString *nameAtt = [[NSAttributedString alloc]initWithString:@"|" attributes:@{NSForegroundColorAttributeName:getColor(mainColor)}];
    [attStr appendAttributedString:nameAtt];
    [attStr appendAttributedString:[[NSAttributedString alloc] initWithString:name]];
    return attStr;
}

#pragma mark -  UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ShopGoodListViewController *vc = [ShopGoodListViewController new];
    vc.tlm_id = self.menuArray[indexPath.row][@"tlm_id"];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(SCREEN_WIDTH / 3 , 113 / WIDTH_5S_SCALE);
}


#pragma mark - data

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray  = @[
                        ].mutableCopy;
    }
    return _dataArray;
}

- (NSArray *)menuArray{
    if (!_menuArray) {
        _menuArray = @[];
    }
    return _menuArray;
}

- (void)setLmId:(NSString *)lmId{
    _lmId = lmId;
    [self getTitleData];
}

- (NSArray *)screeningArray{
    if (!_screeningArray) {
        _screeningArray = @[];
    }
    return _screeningArray;
}

@end
